package com.ashin;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class HttpClient {

    private static final Logger logger = LoggerFactory.getLogger(HttpClient.class);
    public static CloseableHttpClient httpClient = null;
    public static HttpClientContext context = null;
    public static CookieStore cookieStore = null;
    public static RequestConfig requestConfig = null;
    public static String inputEncoding = "utf-8";
    public static String outEncoding = "utf-8";
    // private static Integer connectTimeout = 1000 *5;// 2秒
    // private static Integer connectionRequestTimeout = 1000 *1;// 1秒

    private static int connectionRequestTimeout = 1000 * 2;

    private static int connectTimeout = 1000 * 3;

    private static int socketTimeout = 1000 * 5;

    private static int maxTotal = 2000; // 最大连接数
    private static int defaultMaxPerRoute = 500; // 每个路由最大连接

    static {
        init();
    }

    private static void init() {
        PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager();
        httpClientConnectionManager.setMaxTotal(maxTotal);
        httpClientConnectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);

        context = HttpClientContext.create();
        cookieStore = new BasicCookieStore();
        // 配置超时时间（连接服务端超时1秒，请求数据返回超时2秒）
        requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).setConnectionRequestTimeout(connectionRequestTimeout).build();
        // 设置默认跳转以及存储cookie
        httpClient = HttpClientBuilder.create().setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()).setRedirectStrategy(new DefaultRedirectStrategy()).setDefaultRequestConfig(requestConfig).setConnectionManager(httpClientConnectionManager).setDefaultCookieStore(cookieStore).build();
        
//        new IdleConnectionMonitorThread(httpClientConnectionManager).start();;
        
    }

    /**
     * http get
     * 
     * @param url
     * @return response
     * @throws ClientProtocolException
     * @throws IOException
     * @throws ParseException
     */
    public static String get(String url, Map<String, String> headerMap)
            throws ClientProtocolException, IOException, ParseException {
        String str = "";
        HttpGet httpget = new HttpGet(url);
        for (Map.Entry<String, String> entry : headerMap.entrySet()) {
            httpget.setHeader(entry.getKey(), entry.getValue());
        }

        CloseableHttpResponse response = httpClient.execute(httpget, context);
        try {
            cookieStore = context.getCookieStore();
            List<Cookie> cookies = cookieStore.getCookies();
            for (Cookie cookie : cookies) {
                logger.debug("key:" + cookie.getName() + "  value:" + cookie.getValue());
            }
            str = HttpClient.toString(response);
        } finally {
            // response.close();
            if (null != response) {
                try {
                    EntityUtils.consume(response.getEntity());
                    response.close();
                } catch (IOException e) {
                    logger.error("释放链接错误", e);

                }
            }
        }

        return str;

    }

    /**
     * http post
     * 
     * @param url
     * @param parameters
     *            json
     * @return response
     * @throws ClientProtocolException
     * @throws IOException
     * @throws ParseException,Exception
     */
    public static String postJson(String url, Map<String, Object> params, Map<String, String> headerMap)
            throws ClientProtocolException, IOException, ParseException, Exception {

        logger.info("params:={},headerMap={}", JSON.toJSONString(params), JSON.toJSONString(headerMap));
        String javaTimeRes = "";
        String str = "";
        HttpPost httpPost = new HttpPost(url);
        JSONObject jsonParam = new JSONObject();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            jsonParam.put(entry.getKey(), entry.getValue());
        }
        logger.info("发送请求前的参数jsonParam={}", JSON.toJSONString(jsonParam));
        StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");// 解决中文乱码问题
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        for (Map.Entry<String, String> entry : headerMap.entrySet()) {
            httpPost.setHeader(entry.getKey(), entry.getValue());
        }
        CloseableHttpResponse response = httpClient.execute(httpPost, context);
        try {
            cookieStore = context.getCookieStore();
            List<Cookie> cookies = cookieStore.getCookies();
            for (Cookie cookie : cookies) {
                logger.debug("key:" + cookie.getName() + "  value:" + cookie.getValue());
            }
            str = HttpClient.toString(response);
        } finally {
            if (null != response) {
                try {
                    EntityUtils.consume(response.getEntity());
                    response.close();
                } catch (IOException e) {
                    logger.error("释放链接错误", e);

                }
            }

        }

        return str;
    }

    /**
     * http post
     * 
     * @param url
     * @param parameters
     *            json
     * @return response
     * @throws ClientProtocolException
     * @throws IOException
     * @throws ParseException,Exception
     */
    public static String postJson(String url, Map<String, Object> params)
            throws ClientProtocolException, IOException, ParseException, Exception {
        logger.info("params:={}", JSON.toJSONString(params));
        String str = "";
        HttpPost httpPost = new HttpPost(url);
        JSONObject jsonParam = new JSONObject();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            jsonParam.put(entry.getKey(), entry.getValue());
        }
        logger.info("发送请求前的参数jsonParam={}", JSON.toJSONString(jsonParam));
        StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");// 解决中文乱码问题
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);

        CloseableHttpResponse response = httpClient.execute(httpPost, context);
        try {
            cookieStore = context.getCookieStore();
            List<Cookie> cookies = cookieStore.getCookies();
            for (Cookie cookie : cookies) {
                logger.debug("key:" + cookie.getName() + "  value:" + cookie.getValue());
            }
            str = HttpClient.toString(response);
        } finally {
            // response.close();
            if (null != response) {
                try {
                    EntityUtils.consume(response.getEntity());
                    response.close();
                } catch (IOException e) {
                    logger.error("释放链接错误", e);

                }
            }
        }

        return str;
    }

    /**
     * http post
     * 
     * @param url
     * @param parameters
     *            json
     * @return response
     * @throws ClientProtocolException
     * @throws IOException
     * @throws ParseException,Exception
     */
    public static Map<String, Object> postJsonM(String url, Map<String, Object> params, String encodType)
            throws ClientProtocolException, IOException, ParseException, Exception {
        logger.info("tid={},params:={},url={}", JSON.toJSONString(params), url);
        Map<String, Object> resMap = null;
        HttpPost httpPost = new HttpPost(url);
        JSONObject jsonParam = new JSONObject();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            jsonParam.put(entry.getKey(), entry.getValue());
        }
        logger.info("发送请求前的参数jsonParam={}", JSON.toJSONString(jsonParam));
        StringEntity entity = new StringEntity(jsonParam.toString(), encodType);// 解决中文乱码问题
        entity.setContentEncoding(encodType);
        entity.setContentType("application/json");
        httpPost.setEntity(entity);

        CloseableHttpResponse response = httpClient.execute(httpPost, HttpClientContext.create());
        try {
//            cookieStore = 
//            List<Cookie> cookies = cookieStore.getCookies();
//            for (Cookie cookie : cookies) {
//                logger.debug("key:" + cookie.getName() + "  value:" + cookie.getValue());
//            }
            resMap = HttpClient.toMap(response);
        } finally {
            if (null != response) {
                try {
                    EntityUtils.consume(response.getEntity());
                    response.close();
                } catch (IOException e) {
                    logger.error("释放链接错误", e);

                }
            }

        }

        return resMap;
    }

    /**
     * http post
     * 
     * @param url
     * @param parameters
     * 
     * @return response
     * @throws ClientProtocolException
     * @throws IOException
     * @throws ParseException,Exception
     */
    public static Map<String, Object> postFrom(String url, Map<String, Object> params, Map<String, String> headerMap)
            throws ClientProtocolException, IOException, ParseException, Exception {
        logger.info("params:={},url={}", JSON.toJSONString(params), url);
        Map<String, Object> resMap;
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
            pairList.add(pair);
        }
        httpPost.setEntity(new UrlEncodedFormEntity(pairList, inputEncoding));
        for (Map.Entry<String, String> entry : headerMap.entrySet()) {
            httpPost.setHeader(entry.getKey(), entry.getValue());
        }
        CloseableHttpResponse response = httpClient.execute(httpPost, context);
        try {
            cookieStore = context.getCookieStore();
            List<Cookie> cookies = cookieStore.getCookies();
            for (Cookie cookie : cookies) {
                logger.debug("key:" + cookie.getName() + "  value:" + cookie.getValue());
            }
            resMap = HttpClient.toMap(response);
        } finally {
            if (null != response) {
                try {
                    EntityUtils.consume(response.getEntity());
                    response.close();
                } catch (IOException e) {
                    logger.error("释放链接错误", e);

                }
            }
        }

        return resMap;
    }

    /**
     * 手动增加cookie
     * 
     * @param name
     * @param value
     * @param domain
     * @param path
     */
    public void addCookie(String name, String value, String domain, String path) {
        BasicClientCookie cookie = new BasicClientCookie(name, value);
        cookie.setDomain(domain);
        cookie.setPath(path);
        cookieStore.addCookie(cookie);
    }

    /**
     * 把结果console出来
     * 
     * @param httpResponse
     * @throws ParseException
     * @throws IOException
     */
    public static void printResponse(HttpResponse httpResponse) throws ParseException, IOException {
        // 获取响应消息实体
        HttpEntity entity = httpResponse.getEntity();
        // 响应状态
        System.out.println("status:" + httpResponse.getStatusLine());
        System.out.println("headers:");
        HeaderIterator iterator = httpResponse.headerIterator();
        while (iterator.hasNext()) {
            System.out.println("\t" + iterator.next());
        }
        // 判断响应实体是否为空
        if (entity != null) {
            // String responseString = EntityUtils.toString(entity);
            // System.out.println("response length:" + responseString.length());
            // System.out.println("response content:" + responseString.replace("\r\n", ""));
        }
        System.out.println("------------------------------------------------------------------------------------------\r\n");
    }

    /**
     * 把当前cookie从控制台输出出来
     * 
     */
    public static void printCookies() {
        System.out.println("headers:");
        cookieStore = context.getCookieStore();
        List<Cookie> cookies = cookieStore.getCookies();
        for (Cookie cookie : cookies) {
            System.out.println("key:" + cookie.getName() + "  value:" + cookie.getValue());
        }
    }

    /**
     * 检查cookie的键值是否包含传参
     * 
     * @param key
     * @return
     */
    public static boolean checkCookie(String key) {
        cookieStore = context.getCookieStore();
        List<Cookie> cookies = cookieStore.getCookies();
        boolean res = false;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(key)) {
                res = true;
                break;
            }
        }
        return res;
    }

    /**
     * 直接把Response内的Entity内容转换成String
     * 
     * @param httpResponse
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static String toString(CloseableHttpResponse httpResponse) throws ParseException, IOException {

        String resStr = "";
        try {
            // 获取响应消息实体
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                resStr = EntityUtils.toString(entity, outEncoding);
                logger.info("=======>接收POST请求resStr={}", resStr);
                return resStr;
            } else
                return null;
        } finally {
            if (httpResponse != null) {
                httpResponse.close();
            }

        }

    }

    /**
     * 直接把Response内的Entity内容转换成String
     * 
     * @param httpResponse
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static Map<String, Object> toMap(CloseableHttpResponse httpResponse) throws ParseException, IOException {
        // logger.info("=======>接收POST请求response={}",httpResponse.toString());
        String resStr = "";
        Map<String, Object> resMap = null;
        try {
            // 获取响应消息实体
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                resStr = EntityUtils.toString(entity, outEncoding);
                logger.info("=======>接收POST请求resStr={}", resStr);
                resMap = JSON.parseObject(resStr, Map.class);
                return resMap;
            } else
                return null;
        } finally {
            // if(httpResponse != null){
            // httpResponse.close();
            // }

        }

    }

    /**
     * 发起http请求并获取结果
     * 
     * @param requestUrl
     *            请求地址
     * @param requestMethod
     *            请求方式（GET、POST）
     * @param outputStr
     *            提交的数据
     * @return Map<String, String>(通过Map.get(key)的方式获取对象的属性值)
     */
    @SuppressWarnings("unchecked")
    public static Map<String, String> httpRequest(String requestUrl, String requestMethod, String outputStr) {

        Map<String, String> retMap = null;
        StringBuffer buffer = new StringBuffer();

        URL httpurl = null;
        HttpURLConnection httpConn = null;
        try {
            httpurl = new URL(requestUrl);
            httpConn = (HttpURLConnection) httpurl.openConnection();

            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            httpConn.setUseCaches(false);

            httpConn.setRequestMethod(requestMethod);
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

            if ("GET".equalsIgnoreCase(requestMethod)) {
                httpConn.connect();
            }
            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpConn.getOutputStream();
                // 编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.flush();
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;

            retMap = JSON.parseObject(buffer.toString(), Map.class);

        } catch (Exception e) {
            retMap = new HashMap<String, String>();
            retMap.put("reqStatus", "ERROR");
            retMap.put("reqException", e.getMessage());
        } finally {
            if (httpConn != null)
                httpConn.disconnect();
        }
        return retMap;
    }

    /**
     * 发起https请求并获取结果
     * 
     * @param requestUrl
     *            请求地址
     * @param requestMethod
     *            请求方式（GET、POST）
     * @param outputStr
     *            提交的数据
     * @return Map<String, String>(通过Map.get(key)的方式获取对象的属性值)
     */
    public static Map<String, Object> httpsRequest(String requestUrl, String requestMethod, String outputStr, String contentType) {
        Map<String, Object> retMap = null;
        StringBuffer buffer = new StringBuffer();
        try {

            TrustManager[] tm = { new MyX509TrustManager() };

            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            httpUrlConn.setInstanceFollowRedirects(true);
            httpUrlConn.setHostnameVerifier(new MyHostnameVerifier());
            httpUrlConn.setConnectTimeout(5000);
            httpUrlConn.setReadTimeout(20000);

            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);
            if ("text/xml".equals(contentType)) {
                httpUrlConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
            } else if ("application/json".equals(contentType)) {
                httpUrlConn.addRequestProperty("Content-Type", "application/json");
                httpUrlConn.addRequestProperty("Accept", "application/json");
            }

            if ("GET".equalsIgnoreCase(requestMethod)) {
                httpUrlConn.connect();
            }
            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();

            retMap = JSON.parseObject(buffer.toString(), Map.class);

        } catch (Exception e) {
            logger.error("http请求发生异常", e);
        }

        return retMap;
    }

    public static long logStr2date(String logTimestamp) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return format.parse(logTimestamp).getTime();
    }
    
    public static class IdleConnectionMonitorThread extends Thread {

        private final HttpClientConnectionManager connMgr;
        private volatile boolean shutdown;

        public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {
            super();
            this.connMgr = connMgr;
        }

        @Override
        public void run() {
            try {
                while (!shutdown) {
                    synchronized (this) {
                        wait(5000);
                        // 关闭失效的连接
                        connMgr.closeExpiredConnections();
                        // 可选的, 关闭30秒内不活动的连接
                        connMgr.closeIdleConnections(30, TimeUnit.SECONDS);
                    }
                }
            } catch (InterruptedException ex) {
                // terminate
            }
        }

        public void shutdown() {
            shutdown = true;
            synchronized (this) {
                notifyAll();
            }
        }

    }

}
